from django.shortcuts import render
from .models import *
from rest_framework.response import Response
from AnsibleGUI.settings import MEDIA_ROOT
import json
from rest_framework import generics,status
from webapp.serializer import HostListSerializer
from .serializer import *
from common.Uncompress import untar
from django_filters.rest_framework import DjangoFilterBackend
from common.Pagenate import LargeResultsSetPagination
from rest_framework.views import APIView
from rest_framework.response import Response
from django.http import JsonResponse
from common.AnsibleExec import AnsibleExec
from rest_framework import authentication, permissions
from django.contrib.auth.models import User
from common.PlaybookGen import *

class AppRun(APIView):
    def get(self, request, *args, **kwargs):
        pk = kwargs.get('pk')
        playbook = PlaybookGen(AppId=pk)
        response = playbook.RunPlaybook()
        return JsonResponse({"message": "Command is received!", "data": response})

class AppCatalogListView(generics.ListCreateAPIView):
    queryset = AppCatagory.objects.all()
    serializer_class = AppCatagorySerializer

class AppCatalogDetailView(generics.RetrieveUpdateDestroyAPIView):
    queryset = AppCatagory.objects.all()
    serializer_class = AppCatagorySerializer

class AppsListView(generics.ListCreateAPIView):
    queryset = App.objects.all()
    serializer_class = AppsSerializer
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ['appcatagory']
    paginator = LargeResultsSetPagination()

class AppsDetailView(generics.RetrieveUpdateDestroyAPIView):
    queryset = App.objects.all()
    serializer_class = AppsSerializer

    def handle_uploaded_file(self,uploadfile,group_name):
        untar(uploadfile,group_name)

    def patch(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = AppsSerializer(instance,data=request.data, partial=True)
        if serializer.is_valid():
            serializer.save()
            self.handle_uploaded_file(str(instance.scripts), instance.name)
        return self.partial_update(request, *args, **kwargs)

class AppConfigDetailView(generics.RetrieveUpdateDestroyAPIView):
    queryset = AppConfig.objects.all()
    serializer_class = AppConfigSerializer

class AppConfigListView(generics.ListCreateAPIView):
    queryset = AppConfig.objects.all()
    serializer_class = AppConfigSerializer
    filter_backends = [DjangoFilterBackend]
    ordering_fields = ('id')
    filterset_fields = ['app']
    paginator = LargeResultsSetPagination()


